package com.example.controller;

import com.example.Utils.CookieUtil;
import com.example.Utils.UUIDUtil;
import com.example.entity.User;
import com.example.service.UserService;
import com.example.vo.LoginVo;
import com.example.vo.RespBean;
import com.example.vo.RespBeanEnum;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@Controller
@Slf4j

public class LoginController {

    @Autowired
    private UserService userService;


    // redis注入
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    // redis注入
    @RequestMapping("/tologin")
    public String toLogin() {

        return "login";
    }

    @RequestMapping(value = "/dologin")
    @ResponseBody

    public RespBean doLogin(HttpServletRequest request, HttpServletResponse response) throws JsonProcessingException {
        LoginVo loginvo = new LoginVo();
        loginvo.setMobile("133");
        loginvo.setPassword("123");
        log.info("hello:{}", loginvo);
        log.info("hello:" + loginvo);

        User user = new User();
        user.setUserName("123");
        user.setTel("133");
        user.setName("zhangsan");
        user.setID(1);

        List<User> list = userService.findAll();
        log.info(list + "");
        //生成cookie
        String ticket = UUIDUtil.uuid();

        System.out.println("ticket=========" + ticket);


        request.getSession().setAttribute(ticket, user);
        //注入 redis
        String jsonuser = new ObjectMapper().writeValueAsString(user);

        redisTemplate.opsForValue().set(ticket, jsonuser, 10, TimeUnit.MINUTES);

        CookieUtil.addCookie(response, "userticket", ticket, 10000);


        log.info("========");
        log.info(ticket);
        return RespBean.success(RespBeanEnum.Success);
    }


}


